var app = getApp()
Page({
  data: {
    nocheckIconUrl: '../../images/icon_nocheck.png',
    checkIconUrl: '../../images/icon_checked_red.png',
    shopname: '',
    checkedAll: false,
    delDisabled: false,
    isEdit: false,
    // cartList: [],
    sumPrice: 0,
    showLoading: true,
    noMoretip: false,
    page: 0,
    isloading: false,
    isShowNummodal: false
  },
  onLoad: function () {
    var that = this;
    var page = that.data.page;
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_cart_list',
        page: page
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          var allArr = [];
          var initArr = that.data.cartList;
          var curArr = res.data.data;
          var lastPageLength = curArr.length;
          if (page > 0) {
            allArr = initArr.concat(curArr);
          } else {
            allArr = res.data.data;
          }
          for (let i = 0; i < allArr.length; i++) {
            allArr[i].limitNum = parseInt(allArr[i].limitNum);
            allArr[i].smallNum = parseInt(allArr[i].smallNum);
          }
          that.setData({
            cartList: allArr,
            checkedAll: false,
            sumPrice: 0
          })
          console.log(that.data.checkedAll)
          if (lastPageLength < 10) {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
        } else {
          if (page <= 0) {
            that.setData({
              cartList: [],
              checkedAll: false,
              sumPrice: 0
            })
          } else {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }

        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'shopInfoname',
      success: function (res) {
        that.setData({
          shopname: res.data
        })
      }
    })
    that.getSlient();
    that.onPullDownRefresh();
    console.log(app.globalData.requestUrl);
    that.setData({
      isHasunionid: app.globalData.isHasunionid,
      haveVcmCard: app.globalData.haveVcmCard
    });
    app.setCartnum();//更新购物车数量
  },
  isCheckedAll: function () {
    var that = this;
    var checkState = !that.data.checkedAll;
    var delState;
    if (checkState) {
      delState = true;
    } else {
      delState = false;
    }
    that.setData({
      checkedAll: checkState,
      delDisabled: delState
    })
    var cartList = that.data.cartList;
    for (var i = 0; i < cartList.length; i++) {
      if (checkState) {
        cartList[i].checked = true;
      } else {
        cartList[i].checked = false;
      }
    }
    that.setData({
      cartList: cartList
    })
    that.getSumprice();
  },
  isedit: function (e) {
    var that = this;
    var type = e.target.dataset.type;
    if (type == 'finish') {
      that.getSumprice();
    }
    var isedit = !that.data.isEdit;
    var cartList = that.data.cartList;
    var checkLength = 0;
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].checked) {
        checkLength++
      }
    }
    console.log(checkLength);
    var delDisabled;
    if (checkLength > 0) {
      delDisabled = true;
    } else {
      delDisabled = false;
    }
    that.setData({
      isEdit: isedit,
      delDisabled
    })
  },
  changeNum: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var cartid = e.currentTarget.dataset.cartid;
    var gfid = e.currentTarget.dataset.gfid;
    var gid = e.currentTarget.dataset.gid;
    var smallnum = e.currentTarget.dataset.smallnum;
    smallnum = smallnum > 1 ? parseInt(smallnum) : 1;
    var cartList = that.data.cartList;
    var curIndex = '';
    for (var i = 0; i < cartList.length; i++) {
      if (cartid == cartList[i].id) {
        curIndex = i;
      }
    }
    var curNum = cartList[curIndex].num;
    var stock = cartList[curIndex].stock;
    var isLimit = cartList[curIndex].isLimit;
    var limitNum = parseInt(cartList[curIndex].limitNum);
    if (type == 'add') {
      if (isLimit == 1) {
        if (curNum <= limitNum) {
          curNum++;
        } else {
          if (limitNum > 0) {
            curNum = limitNum;
          }
        }
        if (curNum > limitNum) {
          app.errorTip(that, '超出购买限制', 2000);
          return;
        }
      } else {
        if (curNum <= stock) {
          curNum++;

        } else {
          if (stock > 0) {
            curNum = stock;
          }
        }
        if (curNum > stock) {
          app.errorTip(that, '超出库存数量', 2000);
          return;
        }
      }
    } else {
      if (curNum > smallnum) {
        curNum--;
      } else {
        curNum = smallnum;
        app.errorTip(that, '宝贝不能再减少了哦', 2000);
        return;
      }
    }

    var data = {
      map: 'applet_add_cart',
      gid: gid,
      gfid: gfid,
      num: curNum
    }
    if (curNum >= 1 && !that.data.isloading && curNum <= stock) {
      that.requestCartnum(data, curIndex);
    }
  },
  showChangenum: function (e) {
    var that = this;
    var cartid = e.currentTarget.dataset.cartid;
    var gfid = e.currentTarget.dataset.gfid;
    var gid = e.currentTarget.dataset.gid;
    var cartList = that.data.cartList;
    var curIndex = '';
    for (var i = 0; i < cartList.length; i++) {
      if (cartid == cartList[i].id) {
        curIndex = i;
      }
    }
    var curNum = cartList[curIndex].num;
    var curEditnum = {
      gfid: gfid,
      gid: gid,
      stock: cartList[curIndex].stock,
      isLimit: cartList[curIndex].isLimit,
      limitNum: cartList[curIndex].limitNum,
      smallNum: cartList[curIndex].smallNum,
      curIndex: curIndex
    }
    that.setData({
      curEditnum: curEditnum,
      curNum: curNum,
      isShowNummodal: true
    })
  },
  hideChangenum: function () {
    var that = this;
    that.setData({
      isShowNummodal: false
    })
  },
  changeEditNum: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var disabled = e.currentTarget.dataset.disabled;
    if (disabled) return;
    var curEditnum = that.data.curEditnum;
    var curNum = that.data.curNum;
    var curIndex = that.data.curEditnum.curIndex;
    var cartList = that.data.cartList;
    var stock = cartList[curIndex].stock;
    var isLimit = cartList[curIndex].isLimit;
    var limitNum = cartList[curIndex].limitNum;
    if (type == 'add') {
      if (isLimit == 1) {
        if (curNum < limitNum) {
          curNum++;
        } else {
          curNum = limitNum;
          app.errorTip(that, '超出购买限制', 2000);
        }
      } else {
        if (curNum < stock) {
          curNum++;
        } else {
          curNum = stock;
          app.errorTip(that, '超出库存数量', 2000);
        }
      }
    } else {
      if (curNum > 1) {
        curNum--;
      } else {
        curNum = 1;
        return;
      }
    }
    that.setData({
      curNum: curNum
    })
  },
  numChange: function (e) {
    var that = this;
    var stock = that.data.curEditnum.stock;
    var isLimit = that.data.curEditnum.isLimit;
    var limitNum = that.data.curEditnum.limitNum;
    var val = e.detail.value;
    val = val.replace(/\D/g, '');
    if (isLimit == 1) {
      if (parseInt(val) > parseInt(limitNum)) {
        app.errorTip(that, '超出购买限制', 2000);
        val = limitNum;
      }
    } else {
      if ((parseInt(val)) > parseInt(stock)) {
        app.errorTip(that, '超出库存数量', 2000);
        val = stock;
      }
    }
    that.setData({
      curNum: val
    })
  },
  confirmEditNum: function () {
    var that = this;
    var curEditnum = that.data.curEditnum;
    var curNum = that.data.curNum;
    var curIndex = that.data.curEditnum.curIndex;
    var data = {
      map: 'applet_add_cart',
      gid: curEditnum.gid,
      gfid: curEditnum.gfid,
      num: curNum
    }
    if (curNum > 0) {
      that.requestCartnum(data, curIndex);
    } else {
      app.errorTip(that, '请输入正确的商品数量', 2000);
    }
  },
  requestCartnum: function (data, index) {
    var that = this;
    var cartList = that.data.cartList;
    that.setData({
      isloading: true
    })
    //发起请求，获取列表列表
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          cartList[index].num = data.num;
          that.setData({
            cartList: cartList,
            isShowNummodal: false
          })
          that.getSumprice();
          app.globalData.requestCartNum = res.data.data.cartNum;
          app.setCartnum();//更新购物车数量
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
        wx.hideLoading();
        that.setData({
          isloading: false
        })
      }
    });
  },
  cartGoodChecked: function (e) {
    var that = this;
    var cartid = e.currentTarget.dataset.cartid;
    var cartList = that.data.cartList;
    var curIndex = '';
    var checkedNum = 0;
    var checkedAll;
    var delDisable;
    for (var i = 0; i < cartList.length; i++) {
      if (cartid == cartList[i].id) {
        cartList[i].checked = !cartList[i].checked;
      }
      if (cartList[i].checked) {
        checkedNum++;
      }
    }
    if (checkedNum == cartList.length) {
      checkedAll = true;
    } else {
      checkedAll = false;
    }
    if (checkedNum > 0) {
      delDisable = true;
    } else {
      delDisable = false;
    }
    that.setData({
      cartList: cartList,
      checkedAll: checkedAll,
      delDisabled: delDisable
    })
    that.getSumprice();
  },
  getSumprice: function () {
    var that = this;
    var cartList = that.data.cartList;
    var sumprice = 0;
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].checked) {
        sumprice += cartList[i].num * cartList[i].price;
      }
    }
    // console.log(sumprice);
    that.setData({
      sumPrice: sumprice.toFixed(2)
    })
  },
  delCart: function (e) {
    var that = this;
    var type = e.target.dataset.type;
    var id = e.target.dataset.id;
    var cartList = that.data.cartList;
    var delArr = [];
    var delTip = '';
    if (type == 'single') {
      delArr.push(id);
      delTip = "确定要删除这个商品吗？";
    } else if (type == 'multi') {
      delTip = "确定要删除选中的商品吗？";
      for (var i = 0; i < cartList.length; i++) {
        if (cartList[i].checked) {
          delArr.push(cartList[i].id);
        }
      }
    }
    var isEmpty = (delArr.length == that.data.cartList.length);
    delArr = delArr.join(',');
    console.log(delArr);
    if (!that.data.delDisabled && type == 'multi') {

    } else {
      wx.showModal({
        title: '',
        content: delTip,
        confirmColor: '#1AAD16',
        success: function (res) {
          if (res.confirm) {
            //发起请求，获取列表列表
            wx.showToast({
              title: '删除中',
              icon: 'loading',
              mask: true,
              duration: 10000
            });
            wx.request({
              url: app.globalData.requestUrl,
              data: {
                map: 'applet_cart_delete',
                // suid: app.globalData.suid,
                ids: delArr
              },
              success: function (res) {
                if (res.data.ec == 200) {
                  console.log(res.data.data);
                  wx.showToast({
                    title: res.data.data.msg,
                    icon: 'success',
                    duration: 2000,
                  })
                  that.onPullDownRefresh();
                  that.getSumprice();
                  console.log(isEmpty);
                  if (isEmpty) {
                    that.setData({
                      isEdit: false,
                      checkedAll: false,
                      sumPrice: 0
                    })
                  }

                  app.globalData.requestCartNum = res.data.data.cartNum;
                  app.setCartnum();//更新购物车数量

                } else {
                  wx.showModal({
                    title: '提示',
                    content: res.data.em,
                    showCancel: false
                  });
                }
              },
              complete: function () {
                wx.hideToast();
              }
            });
            console.log(delArr);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  onPullDownRefresh: function () {
    this.setData({
      page: 0,
      noMoretip: false,
      showLoading: true
    });
    this.onLoad();
    console.log("下拉刷新");
  },
  onReachBottom: function () {
    var that = this;
    console.log("到达页面底部")
    var isMore = that.data.noMoretip;
    var page = that.data.page;
    page++;
    that.setData({
      page: page
    });
    if (isMore) {
      console.log("已完成或正在加载");
    } else {
      that.onLoad();
    }
  },
  getSlient: function () {
    var that = this;
    var slient = app.globalData.slient ? app.globalData.slient : '';
    that.setData({
      slient: slient
    })
  },
  gobuy: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },
  // 获取用户信息
  getuserInfo: function (e) {
    var that = this;
    if (e.detail.userInfo) {
      var userdata = e.detail;
      console.log(userdata);
      var slient = that.data.slient;
      var again = false;
      if (slient == 0) {
        again = true;
      }
      app.getuserInfo(that, userdata, again);
    }
  },
  accountOrder: function () {
    var that = this;
    if (this.data.isHasunionid == 0 && this.data.haveVcmCard == 1) {
      return
    }
    var cartList = that.data.cartList;
    var orderArr = [];
    var delArr = [];
    var data = {};
    data.map = 'applet_order_create';
    // data.suid = app.globalData.suid;
    for (var i = 0; i < cartList.length; i++) {
      var cartObj = {};
      if (cartList[i].checked) {
        cartObj.gid = cartList[i].gid;
        cartObj.gfid = cartList[i].gfid;;
        cartObj.num = cartList[i].num;
        orderArr.push(cartObj);
        delArr.push(cartList[i].id);
      }
    }
    console.log(JSON.stringify(orderArr));
    if (orderArr.length > 0) {
      delArr = delArr.join(',');
      wx.setStorage({
        key: "delCart",
        data: delArr
      })
      data.buys = encodeURI(JSON.stringify(orderArr));
      //发起请求，获取列表列表
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true,
        duration: 10000
      });
      wx.request({
        url: app.globalData.requestUrl,
        data: data,
        success: function (res) {
          if (res.data.ec == 200) {
            console.log(res.data.data);
            wx.setStorage({
              key: "submitOrder",
              data: res.data.data,
              success: function () {
                wx.navigateTo({
                  url: '/pages/waitBuyerPay/waitBuyerPay?ordersource=cartorder'
                })
              }
            })
          } else {
            // wx.showModal({
            //   title: '提示',
            //   content: res.data.em,
            //   showCancel: false
            // });
            app.errorTip(that, res.data.em, 2000);
          }
        },
        complete: function () {
          wx.hideToast();
        }
      });
    } else {
      app.errorTip(that, '请选择要结算的商品', 2000);
    }
  },
  initPage: function () {
    
  },
  goodDetail: function (e) {
    var that = this;
    var goodId = e.currentTarget.dataset.gid;
    var isEdit = that.data.isEdit;
    console.log(!isEdit);
    if (!isEdit) {
      wx.navigateTo({
        url: '/pages/goodDetail/goodDetail?id=' + goodId
      })
    }
  },
  makeCall: function () {
    app.makeCall();
  }
})